import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:chathouse/widgets/base_appbar.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:gallery_saver/gallery_saver.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

import '../util/image_utils.dart';
import '../util/toast_util.dart';
import 'Styles.dart';

class NetworkImageBrowser extends StatefulWidget {
  final List<String> imageUrls;
  int idx;
  bool isDownloaded = false;

  NetworkImageBrowser({required this.imageUrls, required this.idx});

  @override
  _NetworkImageBrowserState createState() => _NetworkImageBrowserState();
}

class _NetworkImageBrowserState extends State<NetworkImageBrowser> {
  int _currentIndex = 0;
  PageController _pageController = PageController(initialPage: 0);

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _pageController = PageController(initialPage: widget.idx);
    _currentIndex = widget.idx;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: getAppBar(title: "圖片瀏覽"),
      body: Stack(
        children: [
          PageView.builder(
            controller: _pageController,
            itemCount: widget.imageUrls.length,
            onPageChanged: (index) {
              setState(() {
                _currentIndex = index;
              });
            },
            itemBuilder: (BuildContext context, int index) {
              return
                  // Image.network(widget.imageUrls[index],
                  //   fit: BoxFit.fitWidth)
                  // ImageUtils.image(widget.imageUrls[index],
                  //     imageType: ImageType.NETWORK,
                  //     fit: BoxFit.fitWidth)
                  Align(
                      alignment: Alignment.center,
                      child: Stack(
                          children:[
                              CachedNetworkImage(imageUrl: widget.imageUrls[index], fit: BoxFit.fitWidth),
                            Positioned(
                              bottom: 0,
                              right: 0,
                              child: DecoratedBox(
                                decoration: BoxDecoration(
                                  color: Colors.black.withOpacity(0.5), // Adjust opacity as needed
                                ),
                                child: IconButton(
                                  icon: Icon(Icons.download, color: Colors.white), // Adjust icon color as needed
                                  onPressed: () {
                                    // Implement your download logic here
                                    String url = widget.imageUrls[index];
                                    String fileName = url.split('/').last;
                                    downloadFile(url, fileName);
                                  },
                                ),
                              ),
                            ),
                          ]
                      )
                  );
            },
          ),
          Positioned(
            bottom: 20,
            left: 0,
            right: 0,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: _buildIndicator(),
            ),
          ),
        ],
      ),
    );
  }

  List<Widget> _buildIndicator() {
    List<Widget> indicators = [];
    for (int i = 0; i < widget.imageUrls.length; i++) {
      indicators.add(Container(
        margin: EdgeInsets.symmetric(horizontal: 4),
        width: 10,
        height: 10,
        decoration: BoxDecoration(
          color: _currentIndex == i ? Styles.mainColor : Colors.black12,
          borderRadius: BorderRadius.circular(5),
        ),
      ));
    }
    return indicators;
  }
}

Future<bool> downloadFile(String url, String saveFileName) async {
  bool result = false;
  // Check and request permission
  var status = await Permission.storage.status;
  if (!status.isGranted) {
    await Permission.storage.request();
  }

  // Get local path
  Directory directory = await getTemporaryDirectory(); // Using temp directory for simplicity

  if (!await directory.exists()) {
    await directory.create(recursive: true);
  }
  if (await directory.exists()) {
    File saveFile = File(directory.path + "/$saveFileName");
    // Start downloading
    try {
      Dio dio = Dio();
      await dio.download(
        url,
        saveFile.path,
        onReceiveProgress: (received, total) {
          if (total != -1) {
            print((received / total * 100).toStringAsFixed(0) + "%");
          }
        },
      );
      print("File downloaded to ${saveFile.path}");

      // Save the image to the gallery
      await GallerySaver.saveImage(saveFile.path, albumName: 'ChatHouse').then((bool? success) {
        print('Image saved to gallery: $success');
        result = success??false;
        if(result){
          ToastUtil.showToast("下載成功");
        }else{
          ToastUtil.showToast("下載失敗：無法存儲到相簿");
        }
      });
    } catch (e) {
      print(e);
      ToastUtil.showToast("下載失敗：未知的原因");
    }
  }else{
    ToastUtil.showToast("下載失敗：無法找到系統目錄。");
  }
  return result;
}